package com.application.controller;


import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
public class PictureController {


    /**
     * 存储图片文件到指定文件当中
     * @param file
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/download")
    public  Result DownLoad(@RequestParam(value = "file") MultipartFile file){
        //  如果前端没有传照片回来
        if(file == null || file.getOriginalFilename()== null) return new Result(Code.SELECT_ERR,null,"查询失败");

        //获取源文件名
        String filename = file.getOriginalFilename();
        //随机生成  文件名称  保证 文件中的图片名称没有重复
        String s = UUID.randomUUID().toString();
        String substring = filename.substring(filename.lastIndexOf("."));
        s = s + substring;
        //将文件存储到指定文件当中
        try {
            file.transferTo(new File("D:\\WXPicture\\"+s));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new Result(Code.SELECT_OK,s,"查询成功");
    }




    @ApiOperation("图片回显")
    @GetMapping("/showPicture")
    public void ShowHead(@RequestParam String id, HttpServletResponse response){
        FileInputStream fis = null;
        try {
            fis=new FileInputStream(
                    new File("D:\\WXPicture\\"+id));

            //输出流写会浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte[] b=new byte[1024];
            int len=0;
            while((len = fis.read(b)) != -1){
                outputStream.write(b,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
